<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ajax</title>

</head>

<body>
  <button>发送请求</button>

</body>
<script>

  let button = document.querySelector("button")
  button.addEventListener("click", async function () {
    let result = await http({
      url: "https://meituan.thexxdd.cn/api/frontpage",
      method: "GET",
      data: {}
    }).catch(err => console.error(err))
    console.log(result)
  })

  // function http({ url, method = "GET", data = {} }) {
  //   return new Promise((resolve, reject) => {
  //     const xhr = new XMLHttpRequest();

  //     xhr.onreadystatechange = function () {
  //       if (xhr.readyState === 4) {
  //         if (xhr.status >= 200 && xhr.status < 300) {
  //           resolve(xhr.response);
  //         } else {
  //           reject(new Error(xhr.statusText));
  //         }
  //       }
  //     };

  //     xhr.onerror = function () {
  //       reject(new Error("Network Error"));
  //     };

  //     if (method === "GET") {
  //       const queryString = Object.entries(data)
  //         .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
  //         .join("&");
  //       xhr.open("GET", `${url}?${queryString}`);
  //       xhr.send();
  //     } else if (method === "POST") {
  //       xhr.open("POST", url);
  //       xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  //       xhr.send(JSON.stringify(data));
  //     } else {
  //       reject(new Error(`Invalid method: ${method}`));
  //     }
  //   });
  // }

  function http({ url, method = "GET", data = {} }) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest()

      xhr.onreadystatechange = function () {
        // console.log(xhr.readyState,"111")
        if (xhr.readyState == 4) {
          // console.log(xhr.status)
          if (xhr.status >= 200 && xhr.status < 300) {
            resolve(JSON.parse(xhr.response));
          } else {
            reject(new Error(xhr.statusText));
          }
        }
      }
      //网络错误
      xhr.onerror = function () {
        reject(Error("NetWork Error"))
      }

      xhr.open(method, url)
      xhr.send()

    })



  }


</script>

</html>